package com.sofwin.controller;

import com.sofwin.Constants;
import com.sofwin.pojo.SysUser;
import com.sofwin.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import javax.servlet.http.HttpSession;

/**
 * @packageName: com.sofwin.controller
 * @user: andyliu
 * @date: 2023/1/4 11:21
 * @email 115176513@qq.com
 * @description: TODO
 */
@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @PostMapping("login")
    public String login(SysUser user, HttpSession session,String code){
        String sessionCode = session.getAttribute("code").toString();
        if(code.equals(sessionCode)) {
            String a = new SimpleHash("MD5", "admin", "123456", 10).toString();
            // 根据用户名和密码查询，看结果是否为1条数据
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName(), user.getLoginPwd());
            try {
                subject.login(token);
            } catch (UnknownAccountException ex) {
                session.setAttribute("msg", "账户不存在");
                return "redirect:index.jsp";
            } catch (LockedAccountException ex) {
                session.setAttribute("msg", "账户已停用");
                return "redirect:index.jsp";
            }
            // 登录日志
            // 记录账户的登录时间，用户名和密码分别为什么，登录是否成功
            SysUser sysUser = userService.queryUserByLoginNameAndPwd(user.getLoginName(), "");
            session.setAttribute(Constants.CURRENT_USER, sysUser);
            return "redirect:index";
        }else{
            return "redirect:index.jsp";
        }
    }
    @GetMapping("logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.CURRENT_USER);
        return "redirect:index.jsp";
    }
}
